import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;


public class TCPServer {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {

		IoAcceptor acceptor = new NioSocketAcceptor();
		acceptor.getFilterChain().addLast("logger", new LoggingFilter());
		acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));
		
		acceptor.setHandler(new RequestHandler());
		acceptor.getSessionConfig().setReadBufferSize(2048);
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
		acceptor.bind(new InetSocketAddress(10001));
		System.out.println("Listening on port 10001...");
	}
}

class RequestHandler extends IoHandlerAdapter {
	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		super.messageReceived(session, message);
		if (message.equals("quit")) {
			session.close();
			return;
		}
		session.write(message.toString());
		System.out.println("Message written...");
		Integer i = null;
		if (session.getAttribute("counter") == null) {
			i = new Integer(1);
			System.out.println("#### " + i);
			session.setAttribute("counter", i);
		} else {
			i = (Integer)session.getAttribute("counter");
			System.out.println("---- " + i);
			session.setAttribute("counter", ++i);
		}
		System.out.println("Current session req. number:" + session.getAttribute("counter"));
	}
	
	@Override
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
		// TODO Auto-generated method stub
		super.sessionIdle(session, status);
		System.out.println("IDLE " + session.getIdleCount(status));
		
		if (session.getIdleCount(status) == 5) {
			System.out.println("Managed session number: " + session.getService().getManagedSessionCount());
			System.out.println("Idle count = 5. Closing session!");
			session.close();
			return;
		}
	}
}